<?php

/**
 * Class SignUtils
 * 签名/验签
 *
 * @package App\Utils
 */
class SignUtils {

	public static function parseSign ($arr, $key) {

		$arr = array_merge($arr, [
			'timestamp' => time(),
			'nonceStr' => static::getNonceStr(),
		]);

		$sign = static::makeSign($arr, $key);

		return array_merge($arr, ['sign' => $sign]);
	}

    public static function getNonceStr($length = 16)
    {
        $chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $str = '';

        for($i = 0; $i < $length; $i++)
        {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    public static function makeSign ($arr, $key) {

        // 排除sign参数
        unset($arr['sign']);

        // 字典序
        ksort($arr);

        // 追加key
        $arr['key'] = $key;

        // 拼接
        $string = [];

        foreach ($arr as $k => $v) {
            if ($k != 'sign' && $v != '' && !is_array($v)) {
                array_push($string, $k . '=' . $v);
            }
        }

        $string = join('&', $string);

        // 哈希并大写
        $sign = strtoupper(md5($string));

        return $sign;
    }

    public static function verifySign ($arr, $secret) {
    	$sign = $arr['sign'];
        return self::makeSign($arr, $secret) == $sign;
    }
}


$params = [
	'appId' => 'fbfc472044a3dd578d901f31',
	'mchUrl' => 'test.com', 
];

$key = '4f5cadd0b03bd7df8ebc359d19fd1574eba829ce';
$params = SignUtils::parseSign($params, $key);

var_dump($params);
